package breaking;

import impsoft.utils.general.Timer;

import java.util.ArrayList;
import java.util.List;

public class BreakHandler {
	private Break[] breaks;
	private Break currentBreak;
	private LogoutHandler logoutHandler;
	private List<Break> breaksFinished = new ArrayList<Break>();
	private Timer startTimer;
	private Timer durationTimer;

	public BreakHandler(Break[] breaks, LogoutHandler logoutHandler) {
		super();
		this.breaks = breaks;
		this.logoutHandler = logoutHandler;
		currentBreak = breaks[0];
		startTimer = new Timer(currentBreak.getStartTime() * 60000);

	}

	public boolean isDurationTimeOver() {
		return durationTimer != null && durationTimer.isUp();
	}

	public void doBreak() throws InterruptedException {
		if (currentBreak != null && hasToBreak()) {
			logoutHandler.logout();

			if (!logoutHandler.isLoggedIn()) {
				durationTimer = new Timer(currentBreak.getDuration() * 60000);
				while (durationTimer.isNotUp()) {
					Thread.sleep(5000);
				}
			}
		}
	}

	public void nextBreak() {
		if (currentBreak != null && isDurationTimeOver()) {
			for (Break theBreak : breaks) {
				if (!breaksFinished.contains(theBreak)) {
					startTimer = new Timer(theBreak.getStartTime() * 60000);
					currentBreak = theBreak;
					return;
				}
			}

			breaksFinished.clear();
			nextBreak();
		}
	}

	public boolean hasToBreak() {
		return startTimer != null && startTimer.isUp();
	}
}
